<template>
  <v-container fluid fill-height class="statistics-wrapper">
    <v-layout row wrap justify-center>
    <v-flex md8 sm10 xs12>
<v-flex md12 sm8 xs12 class="px-2 py-2">
        <v-card color="white">
          <v-card-title class="title card-title-bg">
            <v-icon>update</v-icon>
            <span class="mx-2">当前版本</span>
          </v-card-title>
          <v-divider></v-divider>
          <v-card-text class="subheading">
            <v-layout wrap row>
              <v-flex class="px-3 py-1 version-border" md3 xs6 sm4  v-for="(item, key) of versionItems" :key="item + key">
                <v-flex v-for="(_item, _key) of item" :key="_item + _key" d-flex justify-space-between>
                  <span>{{_item.projectName}} - {{_item.isServer ? '服' : '客'}}:</span>
                  <span class="text-xs-right">{{_item.version}}</span>
                </v-flex>
              </v-flex>
            </v-layout>
          </v-card-text>
        </v-card>
      </v-flex>
      <v-flex md12 sm8 xs12 class="px-2 py-2">
        <v-card color="white" height="100%">
          <v-card-title class="title card-title-bg">
            <v-icon>assignment</v-icon>
            <span class="mx-2">{{new Date().getFullYear()}}年{{new Date().getMonth() + 1}}月工作简报</span>
          </v-card-title>
          <v-divider></v-divider>
          <v-card-text class="title">
            <p v-html="briefText" class="my-0 brief-text">
            </p>
          </v-card-text>
        </v-card>
      </v-flex>
      <v-flex md12 class="mx-1 my-3">
        <v-card color="white">
          <v-card-title class="title card-title-bg">
            <v-icon>pie_chart</v-icon>
            <span class="mx-2">本月版本统计</span>
          </v-card-title>
          <v-divider></v-divider>
          <v-card-text class="subheading">
            <v-layout justify-center>
              <v-flex xs12 justify-center d-flex>
                <div id="chart1" ref="chartRef" style="width: 100%;height:540px;" v-resize="chartResize"></div>
              </v-flex>
            </v-layout>
          </v-card-text>
        </v-card>
      </v-flex>
    </v-flex>
    </v-layout>
  </v-container>
</template>

<script>
import echarts from "echarts";
import * as overview from "../../api/overview";
import { getToday, getMonthDay } from "../../util";
import * as demand from "../../api/demand";
import { mapState } from "vuex";

export default {
  data: () => ({
    tabs: null,
    btnToggle: null,
    showProgress: false,
    dialog: false,
    modal: false,
    modalText: "",
    userCos: {},
    usageCos: {},
    versions: {},
    chart1: null,
    option1: null,
    briefText: "",
    versionItems: {},
    PROJECT: []
  }),
  computed: {
    ...mapState(["state_projects", "state_departments"])
  },
  mounted() {
    let _this = this
    // this.getProjectList();
    $Vue.$off('PROJECTS_GOT')
    $Vue.$on('PROJECTS_GOT', function(data) {
      _this.PROJECT = _.slice(_this.state_projects);
      _this.getOverviewData();
    })
    $Vue.$off('areaCodeChange')
    $Vue.$on('areaCodeChange', ()=>{
    this.getOverviewData();
    })
    $Vue.$off('AREAS_READY')
    $Vue.$on('AREAS_READY', ()=>{
      this.getOverviewData();
    })

    this.getOverviewData();
    
    this.chart1 = echarts.init(document.getElementById("chart1"));
    this.option1 = {
      color: ["#21749f", "#009688", "#004D40"],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true
      },
      xAxis: [
        {
          type: "category",
          axisLabel: {
            interval: 0
          },
          data: [
            "经典斗牛",
            "斗公牛",
            "红中麻将",
            "点子牛",
            "欢乐金花",
            "三公",
            "跑得快",
            "长沙麻将",
            "平江扎鸟"
          ],
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: "value",
          minInterval: 1
        }
      ],
      series: [
        {
          name: "修改次数",
          type: "bar",
          barWidth: "24%",
          itemStyle: {
            normal: {
              barBorderRadius: [10, 10, 0, 0]
            }
          },
          label: {
            normal: {
              show: false,
              position: "outside",
              fontSize: 14
            }
          },
          data: [8, 8, 8, 8, 8, 8, 8, 8, 8]
        }
      ]
    };
    this.chart1.setOption(this.option1);
  },
  watch: {
    // 监测路由参数变化
    $route(to, from) {
      console.log(to.params.gametype);
    }
  },
  methods: {
    getToday,
    getProjectList() {
      demand.getProjectList.r().then(({ data }) => {
        let d = data.data;
        if (data.result == 0) {
          let projects = {};
          _.forEach(d.dataList, (item, i) => {
            projects[item.id] =
              item.projectName + (item.type == 1 ? "-客户端" : "-服务端");
          });
        }
      });
    },
    getOverviewData() {
      overview.getOverviewData.r().then(({ data }) => {
        // console.log(JSON.stringify(data));

        let d = data.data;
        if (data.result == 0) {
          let r = {};
          d.versionList.forEach((item, i) => {
            if (item.type !== 0) {
              r[item.project] = {};
              r[item.project][item.type] = {};
            }
          });
          d.versionList.forEach((item, i) => {
            if (item.type !== 0) {
              r[item.project][item.type] = {
                projectName: item.projectName,
                version: item.versionNumber,
                isServer: item.type == 2
              };
            }
          });

          this.versionItems = r;
          // console.error(r)
          let legendData = [];
          let ds =  _.sortBy(d.gameList, 'totalCount').reverse()
          // let ds = d.gameList.sort((a, b)=>{
          //   return  b.totalCount > a.totalCount
          // })
          // d.gameList = d.gameList.reverse()
          _.forEach(ds, (item, key) => {
            legendData.push(item.gameType);
          });
          this.chart1.setOption({
            series: [
              {
          name: "修改次数",
          type: "bar",
          barWidth: "16%",
          itemStyle: {
            normal: {
              barBorderRadius: [10, 10, 0, 0]
            }
          },
          label: {
            normal: {
              show: false,
              position: "outside",
              fontSize: 14
            }
          },
          data: this.convertDataMonth(ds)
        }
            ],
            xAxis: [
        {
          type: "category",
          data: legendData,
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
          });
          this.briefText = this.buildBrief(d.recordList);

        } else {
        }
      });
    },
    chartResize(ev) {
      if (this.chart1) {
        if (window.screen > 414) {
          this.chart1.resize();
        }
      }
    },
    buildBrief(record) {
      if (!record) return "暂未更新简报";
      let brief = "";
    
      record = _.filter(record, (item)=>{
        if(window._PROJECTS[item.projectName]){
          return !_PROJECTS[item.projectName].match('其他')  
        }
        return false
      })
      
      // 最近五个版本
      record.forEach((item, i) => {
        brief += `${window._PROJECTS[item.projectName] ?window._PROJECTS[item.projectName] :''}于${getMonthDay(
          item.updateTime
        )}发布新版本，版本号：${item.versionNumber}。 <br/>`;
      });
      // console.error(brief)
      return brief;
    },
    convertDataMonth(data) {
      if (!data) return [];
      var chart = [];
      data.forEach(function(item, index) {
        chart.push({
          name: item.gameType,
          value: item.totalCount
        });
      });
      return chart;
    }
  }
};
</script>

<style lang="less" scoped>
.version-border {
  border: 1px dashed #ddd;
  border-radius: 24px;
}
.brief-text {
  line-height: 1.4em;
}
</style>


